import hashlib
import json
import requests
import time
from functools import wraps
import os
from typing import List
from .parameModel import rjPutParamsModel  # type:ignore


class pre_api_get:
    def __init__(self):
        self.appkey = "1bN0kRdX8DVPGGvD5UdP"
        self.appSecret = "LzHQEv5nH8umSviagRdhK3lAJrYSMJpqe8QDuO8o"
        self.openid = "kjvb46f04fZ4uHQAbBBM"
        self.api = "https://gateway.rjmart.cn/open/shop"
        self.pre_api = "https://gateway.test.rj-info.com/open/shop"
        module_path = os.path.abspath(__file__)
        self.module_dir = os.path.dirname(module_path)
        # if not os.path.exists(f"{self.module_dir}/cx/get_json"):
        #     os.makedirs(f"{self.module_dir}/cx/get_json")

    # 获取Authorization_Code
    def get_Authorization_Code(self):
        """获取Authorization_Code"""
        url = "https://www.rjmart.cn/auth/oauth/authorize"
        response = requests.get(url=url)
        return response

    # 通过Authorization_Code获取Access_Token
    def ac_get_Access_Token(self):
        """通过Authorization_Code获取Access_Token"""
        url = "https://www.rjmart.cn/auth/oauth/token"
        response = requests.post(url=url)
        return response

    # 通过openid获取Access_Token
    def openid_Access_Token(self):
        """通过openid获取Access_Token"""
        url = "https://www.rjmart.cn/auth/openid/login"
        md5 = hashlib.md5()
        md5.update(self.appSecret.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        data = {"openid": self.openid, "sign": sign}
        response = requests.post(url=url, data=data)
        results = json.loads(response.content.decode("utf-8"))
        t = time.time()
        results.update({"time": t})
        with open(f"{self.module_dir}/cx/Access_Token_cx.json", mode="w") as f:
            f.write(json.dumps(results))
        return results

    # api基础模板
    def __no_data(self, url, name, data=""):
        """api基础模板"""
        time_now = time.time()
        with open(f"{self.module_dir}/cx/Access_Token_cx.json") as j:
            ac_json = json.load(j)
        Access_Token = ac_json["access_token"]
        time_acc = ac_json["time"]
        if time_now - time_acc > 600:
            Access_Token = self.openid_Access_Token()["access_token"]
        header = {
            "Authorization": f"Bearer {Access_Token}",
            "Content-Type": "application/json;charset=utf-8",
        }
        json_post_data = self.appSecret + data
        md5 = hashlib.md5()
        md5.update(json_post_data.encode("utf-8"))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        s_url = f"{self.api}{url}?appkey={self.appkey}&sign={sign}"
        response = requests.post(url=s_url, data=data.encode("utf-8"), headers=header)
        results = response.content.decode("utf-8")
        # with open(
        #     f"{self.module_dir}/cx/get_json/{name}.json", mode="w", encoding="utf-8"
        # ) as f:
        #     f.write(results)
        return response                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    # 查询所有运费模板
    def findTemplate(self):
        """查询所有运费模板"""
        url = "/openapi/product/findTemplate"
        name = "findTemplate"
        return self.__no_data(url, name)

    # 查询商品标准单位与规格
    def UnitAndSpec(self):
        """查询商品标准单位与规格"""
        url = "/openapi/product/queryUnitAndSpecification"
        name = "UnitAndSpec"
        return self.__no_data(url, name)

    # 查询入驻单位
    def settledOgrList(self):
        """查询入驻单位"""
        url = "/openapi/product/settledOgrList"
        name = "settledOgrList"
        return self.__no_data(url, name)

    # 商品树形分类查询
    def AllCategoryTree(self):
        """商品树形分类查询"""
        url = "/openapi/product/queryAllCategoryTree"
        name = "AllCategoryTree"
        return self.__no_data(url, name)

    # 商品品牌查询
    def getSuppBrands(self):
        """商品品牌查询"""
        url = "/openapi/product/getSuppBrands"
        name = "getSuppBrands"
        return self.__no_data(url, name)

    # 查询商品一级分类的属性（一级分类Id）
    def CategoryAttribute(self, categoryId):
        """查询商品一级分类的属性（一级分类Id）"""
        url = "/openapi/product/queryCategoryAttribute"
        name = "CategoryAttribute" + str(categoryId)
        data = json.dumps({"categoryId": categoryId})
        return self.__no_data(url, name, data=data)

    # 搜索商品列表
    def ProductList(self, data_json):
        """
        批量查询商品（"status" : 3,      2:草稿，3:上架，4下架，5强制下架，12待审核，15已驳回
            *"brandIds" : [2],         品牌列表
            *"categoryId" : 1671,      分类id
            *"productNum" : "202200",  商品货号
            *"productName" : "测试商品"） 商品名
        """
        url = "/openapi/product/queryProductList"
        name = (
            "ProductList" + "&".join(list(map(str, data_json["brandIds"])))
            if data_json.get("brandIds", None)
            else ""
        )
        data = json.dumps(data_json)
        return self.__no_data(url, name, data=data)

    # 查询单个商品内容（id）
    def ProductDetail(self, ProductId):
        """查询单个商品内容（id）"""
        url = "/openapi/product/queryProductDetail"
        name = "ProductDetail" + str(ProductId)
        data = json.dumps({"id": ProductId})
        return self.__no_data(url, name, data=data)

    def ProductsDetailList(self, ProductIds: List[int]):
        """查询多个商品内容(id)
        单次支持查询50个
        """
        url = "/openapi/product/queryByProductIds"
        name = "ProductsDetail" + str(time.time())
        data = json.dumps(ProductIds)
        return self.__no_data(url, name, data=data)
        
    # 上架商品（id_list/code_list）
    def onSale(self, ProductId_list):
        """上架商品（id_list/code_list）"""
        url = "/openapi/product/onSale"
        name = "onSale"
        data = json.dumps({"productIdList": ProductId_list})
        return self.__no_data(url, name, data=data)

    # 删除商品（id_list/code_list）
    def deleteProduct(self, ProductCode_list):
        """删除商品（id_list/code_list）"""
        url = "/openapi/product/deleteProductList"
        name = "deleteProductList"
        data = json.dumps({"productIdList": ProductCode_list})
        return self.__no_data(url, name, data=data)

    # 下架商品（id_list/code_list）
    def offSale(self, ProductId_list):
        """下架商品（id_list/code_list）"""
        url = "/openapi/product/offShelves"
        name = "offSale"
        data = json.dumps({"productIdList": ProductId_list})
        return self.__no_data(url, name, data=data)

    # 撤销商品审核（id_list/code_list）
    def cancelReview(self, ProductId_list):
        """撤销商品审核（id_list/code_list）"""
        url = "/openapi/product/cancelReview"
        name = "cancelReview"
        data = json.dumps({"productIdList": ProductId_list})
        return self.__no_data(url, name, data=data)

    # 单个新增、更新
    def saveOrUpdateProduct(self, json_data: rjPutParamsModel):
        """单个新增、更新"""
        url = "/openapi/product/saveOrUpdateProduct"
        name = "saveOrUpdateProduct"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)

    # 批量新增、更新
    def batchSaveOrUpdateProduct(self, json_data: List[rjPutParamsModel]):
        """批量新增、更新"""
        url = "/openapi/product/batchSaveOrUpdateProduct"
        name = "saveOrUpdateProduct"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)

    # 批量更新（可部分更新）
    def updateProductInfoByCode(self, json_data):
        """批量更新（可部分更新）"""
        url = "/openapi/product/updateProductInfoByCode"
        name = "updateProductInfoByCode"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)

    def batchSaveOrUpdateProductV2(self, json_data):
        """批量新增、更新(新)"""
        url = "/openapi/product/saveProduct"
        name = "saveProduct"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)
    
    def get_queryAttribute(self, json_data):
        """批量新增、更新(新)"""
        url = "/openapi/category/queryAttribute"
        name = "saveProduct"
        data = json.dumps(json_data)
        return self.__no_data(url, name, data=data)
